package com.zhenlong.aop.aspect;

import com.alibaba.fastjson.JSONObject;
import com.zhenlong.aop.annotation.Log;
import com.zhenlong.aop.dao.SysLogDao;
import com.zhenlong.aop.dao.UserLogDao;
import com.zhenlong.aop.domain.SysLog;
import com.zhenlong.aop.domain.UserLog;
import com.zhenlong.aop.util.DateUtil;
import com.zhenlong.aop.util.HttpContextUtils;
import com.zhenlong.aop.util.IPUtils;
import com.zhenlong.aop.vo.FileImportRequest;
import com.zhenlong.aop.vo.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class LogAspect {

    @Autowired
    private SysLogDao sysLogDao;
    @Autowired
    private UserLogDao userLogDao;

    @Pointcut("@annotation(com.zhenlong.aop.annotation.Log)")
    public void pointcut() { }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        Object result = null;
        String exceptionMsg = null;
        long beginTime = System.currentTimeMillis();
        try {
            // 执行方法
            result = point.proceed();
        } catch (Throwable e) {
            exceptionMsg= e.toString();

        }
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        // 保存日志
        saveLog(point, time,exceptionMsg);
        return result;
    }
    @AfterReturning("pointcut()")
    public void returning(JoinPoint point){
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Log logAnnotation = method.getAnnotation(Log.class);
        Object[] args = point.getArgs();
        UserLog userLog = new UserLog();
        User user = new User();
        FileImportRequest fileImportRequest = null;
        if (args[0] instanceof String){
            String result = (String) args[0];
            JSONObject jsonObject = JSONObject.parseObject(result);
            if(jsonObject.containsKey("userId")) {
                userLog.setUserId(jsonObject.getObject("userId", String.class));
            }
            if(jsonObject.containsKey("phoneNum")) {
                userLog.setPhoneNum(jsonObject.getObject("phoneNum", String.class));

            }
            if(jsonObject.containsKey("role")) {
                userLog.setRole(jsonObject.getObject("role", String.class));

            }
            if(jsonObject.containsKey("userName")) {
                userLog.setUserName(jsonObject.getObject("userName", String.class));

            }
        }
        if (args[0] instanceof FileImportRequest){
            fileImportRequest = (FileImportRequest) args[0];
            BeanUtils.copyProperties(fileImportRequest,userLog);
        }else if (args[0] instanceof User){
            user = (User) args[0];
            BeanUtils.copyProperties(user,userLog);
        }

        userLog.setOperDesc("后置通知新增用户操作日志");
        userLog.setOperTime(DateUtil.getTodayToSecond());
        userLog.setOperType(logAnnotation.type().getNameCN());
        userLogDao.insert(userLog);

    }

    /**
     * 只要有 around throwing都不会执行
     * @param point
     */
    //@AfterThrowing("pointcut()")
    public void throwing(JoinPoint point){
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Log logAnnotation = method.getAnnotation(Log.class);
        Object[] args = point.getArgs();
        UserLog userLog = new UserLog();
        User user = new User();
        FileImportRequest fileImportRequest = null;
        if (args[0] instanceof String){
            String result = (String) args[0];
            JSONObject jsonObject = JSONObject.parseObject(result);
            if(jsonObject.containsKey("userId")) {
                userLog.setUserId(jsonObject.getObject("userId", String.class));
            }
            if(jsonObject.containsKey("phoneNum")) {
                userLog.setPhoneNum(jsonObject.getObject("phoneNum", String.class));

            }
            if(jsonObject.containsKey("role")) {
                userLog.setRole(jsonObject.getObject("role", String.class));

            }
            if(jsonObject.containsKey("userName")) {
                userLog.setUserName(jsonObject.getObject("userName", String.class));

            }
        }
        if (args[0] instanceof FileImportRequest){
            fileImportRequest = (FileImportRequest) args[0];
            BeanUtils.copyProperties(fileImportRequest,userLog);
        }else if (args[0] instanceof User){
            user = (User) args[0];
            BeanUtils.copyProperties(user,userLog);
        }

        userLog.setOperDesc("异常新增用户操作日志");
        userLog.setOperTime(DateUtil.getTodayToSecond());
        userLog.setOperType(logAnnotation.type().getNameCN());
        userLogDao.insert(userLog);

    }
    private void saveLog(ProceedingJoinPoint joinPoint, long time, String exceptionMsg) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SysLog sysLog = new SysLog();
        Log logAnnotation = method.getAnnotation(Log.class);
        if (exceptionMsg !=null){
            sysLog.setExceptionMsg(exceptionMsg);
        }
        if (logAnnotation != null) {
            // 注解上的描述
            sysLog.setOperation(logAnnotation.value());
            if (logAnnotation.type()!=null){
                sysLog.setType(logAnnotation.type().getNameCN());
            }else {
                return;
            }
        }

        // 请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");
        // 请求的方法参数值
        User user = new User();
        FileImportRequest fileImportRequest = null;
        Object[] args = joinPoint.getArgs();
        if (args[0] instanceof String){
            String result = (String) args[0];
            JSONObject jsonObject = JSONObject.parseObject(result);
            String batchNum = jsonObject.getObject("batchNum", String.class);
            //fileImportRequest= JSONObject.toJavaObject(JSONObject.parseObject(result),FileImportRequest.class);
            if(jsonObject.containsKey("userId")) {
                user.setUserId(jsonObject.getObject("userId", String.class));
            }
            if(jsonObject.containsKey("phoneNum")) {
                user.setPhoneNum(jsonObject.getObject("phoneNum", String.class));

            }
            if(jsonObject.containsKey("role")) {
                user.setRole(jsonObject.getObject("role", String.class));

            }
            if(jsonObject.containsKey("userName")) {
                user.setUserName(jsonObject.getObject("userName", String.class));

            }

            user.setOperTime(DateUtil.getTodayToSecond());
            user.setOperType(logAnnotation.type().getNameCN());

        }
        else if (args[0] instanceof FileImportRequest){
            fileImportRequest = (FileImportRequest)args[0];
        }
        if (args[0] instanceof User) {
            user = (User) args[0];
            user.setOperTime(DateUtil.getTodayToSecond());
            user.setOperType(logAnnotation.type().getNameCN());
        }

        UserLog userLog = new UserLog();
        BeanUtils.copyProperties(user,userLog);

        // 请求的方法参数名称
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = u.getParameterNames(method);
        System.out.println(paramNames[0]);
        if (args != null && paramNames != null) {
            String params = "";
            for (int i = 0; i < args.length; i++) {
                params += "  " + paramNames[i] + ": " + args[i];
            }
            sysLog.setParams(params);
        }
        // 获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        // 设置IP地址
        sysLog.setIp(IPUtils.getIpAddr(request));
        // 模拟一个用户名
        sysLog.setUsername(userLog.getUserName());
        sysLog.setTime((int) time);
        sysLog.setCreateTime(DateUtil.getTodayToSecond());
        // 保存系统日志
        sysLogDao.insert(sysLog);

        //保存用户操作日志
        userLog.setOperDesc("环绕通知新增用户操作日志");
        userLogDao.insert(userLog);

    }
}
